package com.utils;

import android.content.Context;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class FileHelper {
    private Context context;
    /**
     * SD卡是否存在
     **/
    private boolean hasSD = false;
    /**
     * SD卡的路径
     **/
    private static String SDPATH = "/sdcard/yzf/";
    /**
     * 当前程序包的路径
     **/
    private String FILESPATH;

    public FileHelper(Context context) {
        this.context = context;
        hasSD = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        //		SDPATH = Environment.getExternalStorageDirectory().getPath();
        FILESPATH = this.context.getFilesDir().getPath();
    }

    /**
     * 生成文件夹
     */
    public void makeRootDirectory() {
        File file = null;
        try {
            file = new File(SDPATH);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
        }
    }

    /**
     * 在SD卡上创建文件
     *
     * @throws IOException
     */
    public static File createSDFile(String fileName) throws IOException {
        File file = new File(SDPATH + "//" + fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        return file;
    }

    /**
     * 删除SD卡上的文件
     *
     * @param fileName
     */
    public boolean deleteSDFile(String fileName) {
        File file = new File(SDPATH + "//" + fileName);
        if (file == null || !file.exists() || file.isDirectory())
            return false;
        return file.delete();
    }

    /**
     * 写入内容到SD卡中的txt文本中
     * str为内容
     */
    public static void writeSDFile(String str, String fileName) {
        try {
            FileWriter fw = new FileWriter(SDPATH + "//" + fileName);
            File f = new File(SDPATH + "//" + fileName);
            fw.write(str);
            FileOutputStream os = new FileOutputStream(f);
            DataOutputStream out = new DataOutputStream(os);
            out.writeShort(2);
            out.writeUTF("");
            System.out.println(out);
            fw.flush();
            fw.close();
            System.out.println("====****《" + str + "》****====");
        } catch (Exception e) {
            LogToFile.d("====保存缓存数据错误====", e.getMessage());
        }
    }

    /**
     * 写入内容到SD卡中的txt文本中
     * str为内容
     */
    public static void addWriteSDFile(boolean isAdd, String str, String fileName) {
        FileOutputStream fos = null;//FileOutputStream会自动调用底层的close()方法，不用关闭
        BufferedWriter bw = null;
        try {
            fos = new FileOutputStream(SDPATH + "//" + fileName, isAdd);//这里的第二个参数isAdd代表追加还是覆盖，true为追加，flase为覆盖
            bw = new BufferedWriter(new OutputStreamWriter(fos, Charset.forName("GBK")));
            bw.write(str);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();//关闭缓冲流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存账户余额到本地
     *
     * @param isAdd    是否添加 ture：是添加  false：是覆盖
     * @param str      添加的内容
     * @param fileName 保存的文件位置
     */
    public static void saveMoneySDFile(boolean isAdd, String str, String fileName) {
        try {
            LogToFile.d("====本地缓存====", "开始缓存数据：" + str);
            createSDFile(fileName);
            addWriteSDFile(isAdd, str, fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入内容到SD卡中的txt文本中
     * str为内容
     */
    public static void writeSDFileAppend(String str, String logFileName) {
        LogToFile.d("====保存缓存数====", "开始缓存数据");
        try {
            FileWriter fw = new FileWriter(SDPATH + "//" + logFileName, true);
            File f = new File(SDPATH + "//" + logFileName);
            fw.write(str);
            FileOutputStream os = new FileOutputStream(f);
            DataOutputStream out = new DataOutputStream(os);
            out.writeShort(2);
            out.writeUTF("");
            System.out.println(out);
            fw.flush();
            fw.close();
            LogToFile.d("====保存缓存数====", "开始缓存数据 str = " + str);
        } catch (Exception e) {
            LogToFile.d("====保存缓存数据错误====", e.getMessage());
        }
    }

    /**
     * 读取SD卡中文本文件
     *
     * @param fileName
     * @return
     */
    public static String readSDFile(String fileName) {
        StringBuffer sb = new StringBuffer();
        File file = new File(SDPATH + "//" + fileName);
        try {
            BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
            // FileInputStream fis = new FileInputStream(file);
            int c;
            while ((c = fis.read()) != -1) {
                sb.append((char) c);
            }
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 读取
     *
     * @return
     */
    public static Map<String, String> getSavedBankInfo(String fileName) {
        File file = new File(SDPATH + "//" + fileName);
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String[] res = br.readLine().split("##");
            Map<String, String> map = new HashMap<String, String>();
            map.put("bankname", res[0]);
            map.put("bankprot", res[1]);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取收款条目缓存信息
     *
     * @return
     */
    public static Map<String, String> getSavedReceiptItemInfoMap(String fileName) {
        File file = new File(SDPATH + "//" + fileName);
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String[] res = br.readLine().split(",");
            if (res.length > 0) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("money", res[0]); //存款金额
                map.put("balance", res[1]);   //卡上余额
                map.put("tradingTime", res[2]);   //交易时间
                map.put("payer", res[3]); //存款人
                map.put("payerCard", res[4]); //存款人卡号
                map.put("payerBank", res[5]);//存款人银行
                map.put("mark", res[6]); //唯一标识，重复性验证使用  不同银行可能传的Mark不一样
                map.put("description", res[7]); //备注
                map.put("systemDescription", res[8]); //系统备注
                map.put("numbered", res[9]); //银行流水号
                return map;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}